﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Web.Mvc;
using AFT.Parking.Bizlogic.ConstructionInfo;
using AFT.Parking.Entity;
using AFT.Parking.Entity.ArgumentEntity;
using AFT.Parking.Foundation.Utilities;
using AFT.Parking.WebSite.Common;
using AFT.Parking.WebSite.Filter;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using FileHelper = AFT.Parking.WebSite.Common.FileHelper;

namespace AFT.Parking.WebSite.Controllers
{
    public class QualityRecordController : BaseController
    {
        private readonly ConstructionInfoBiz _constructionInfoBiz;

        public QualityRecordController()
        {
            _constructionInfoBiz = new ConstructionInfoBiz();
        }

        [HttpGet, AdminOnly]
        public ActionResult List(string name, int page = 1)
        {
            Expression<Func<QualityRecord, bool>> exp = u => true;
            if (!string.IsNullOrEmpty(name))
            {
                exp = u => u.Name.Contains(name);
            }
            var p = new PaginationParam<QualityRecord>
            {
                Expression = exp,
                PageSize = 20,
                PageIndex = page,
                OrderByList = new List<OrderBy<QualityRecord>>
                    {
                        new OrderBy<QualityRecord> {Sort = false, exp = u => u.LastModifiedTime}
                    }
            };
            var list = _constructionInfoBiz.GetList<QualityRecord>(p);
            return View(list);
        }

        [HttpGet, AdminOnly]
        public ActionResult Register(int id = 0)
        {
            var model = id == 0 ? new QualityRecord() : _constructionInfoBiz.GetById<QualityRecord>(id);
            return View(model);
        }

        [HttpPost, AdminOnly]
        public ActionResult Register(QualityRecord record)
        {
            ValidateSercurityModel(record);
            return View(record);
        }

        [HttpGet]
        public ActionResult ScanView(string tagId)
        {
            var record = _constructionInfoBiz.GetQualityRecordByTagId(tagId);
            return View(record);
        }

        [HttpPost, AdminOnly]
        public ActionResult UpLoadFile(string folderName)
        {
            var result = FileHelper.Upload(folderName);
            return Content(JsonConvert.SerializeObject(result));
        }

        [HttpGet, AdminOnly]
        public ActionResult Delete(int id)
        {
            var delItem = _constructionInfoBiz.Remove<QualityRecord>(id);
            var qrcodeImg = Server.MapPath(delItem.ImgUrl);
            if (System.IO.File.Exists(qrcodeImg))
            {
                System.IO.File.Delete(qrcodeImg);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        [HttpGet,AdminOnly]
        public ZipResult ZipQrCode()
        {
            const int zipConvertLevel = 6;
            var folder = Server.MapPath("/Upload/QualityRecord");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            using (var ms = new MemoryStream())
            {
                using (var zipstr = new ZipOutputStream(ms))
                {
                    zipstr.SetLevel(zipConvertLevel);
                    var files = Directory.GetFileSystemEntries(folder);
                    foreach (var fileName in files)
                    {
                        using (var fs = System.IO.File.OpenRead(fileName))
                        {
                            var buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);

                            var entry = new ZipEntry(fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1));
                            zipstr.PutNextEntry(entry);
                            zipstr.Write(buffer, 0, buffer.Length);
                            fs.Flush();
                            fs.Position = 0;
                            fs.Close();
                        }
                    }
                    zipstr.Finish();
                    ms.Position = 0;

                    return new ZipResult(ms)
                    {
                        FileDownloadName = "完成质量二维码.zip"
                    };
                }
            }
        }


        #region private actions
        private void ValidateSercurityModel(QualityRecord record)
        {
            var msg = string.Empty;
            var icon = "error";
            if (string.IsNullOrEmpty(record.Name))
            {
                msg += "标题不能为空";
            }
            if (string.IsNullOrEmpty(record.TagName))
            {
                msg += "二维码名称不能为空";
            }
            if (msg.Length == 0)
            {
                record.TagId = record.TagId ?? Guid.NewGuid().ToString();
                record.ImgUrl = QrCodeHelper.GenerateQrcode("QualityRecord", record.TagId, record.TagName);
                if (_constructionInfoBiz.SaveQualityRecord(record))
                {
                    icon = "success";
                    msg = "保存成功。";
                }
                else
                {
                    msg = "保存失败，存在相同的信息。";
                }
            }
            ViewBag.Message = msg;
            ViewBag.Icon = icon;
        }
        #endregion
    }
}